package com.phuoc.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.phuoc.dao.EstablishmentDAO;
import com.phuoc.dao.TypeOfEstablishmentDAO;
import com.phuoc.entities.Establishment;

public class SearchableActivity extends CustomWindowForList {

	private EstablishmentDAO datasource;
	private TypeOfEstablishmentDAO typeEstabDataSource;

	private List<Establishment> establishments;
	private EstablishmentAdapter adapter1;
	private String query;
	private boolean aToz = true;
	private boolean hideCheckBox = false;

	// Layout
	private LinearLayout layoutDelete;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
		this.setWindowTitle("Search");

		// Open database connection
		datasource = new EstablishmentDAO(SearchableActivity.this);
		datasource.open();
		typeEstabDataSource = new TypeOfEstablishmentDAO(this);
		typeEstabDataSource.open();

		// Find Layout
		layoutDelete = (LinearLayout) findViewById(R.id.layoutDelete);

		// Get the intent, verify the action and get the query
		Intent intent = getIntent();
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			query = intent.getStringExtra(SearchManager.QUERY);
			doMySearch(query);
		}

		// Register for editing
		registerForContextMenu(getListView());
	}

	@Override
	protected void onResume() {
		typeEstabDataSource.open();
		datasource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		typeEstabDataSource.close();
		datasource.close();
		super.onPause();
	}

	// My menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mymenu, menu);
		return true;
	}

	// My menu details
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.itemSearch:
			onSearchRequested();
			break;
		case R.id.itemSort:
			switchSortMode();
			break;
		case R.id.itemDisplay:
			chooseDisplayMode();
			break;

		case R.id.itemDelete:
			layoutDelete.setVisibility(LinearLayout.VISIBLE);
			hideCheckBox = true;
			updateListView();
			break;

		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	public void onClick(View v) {
		@SuppressWarnings("unchecked")
		ArrayAdapter<Establishment> adapter = (ArrayAdapter<Establishment>) getListAdapter();

		switch (v.getId()) {

		case R.id.btnCancel:
			layoutDelete.setVisibility(LinearLayout.GONE);
			hideCheckBox = false;
			updateListView();
			break;

		case R.id.btnDelete:
			ArrayList<String> list = adapter1.getListIdSelected();
			for (int i = 0; i < list.size(); i++) {
				datasource.deleteEstablishmentById(list.get(i));
			}
			layoutDelete.setVisibility(LinearLayout.GONE);
			hideCheckBox = false;
			updateListView();
			break;

		default:
			break;
		}

		// Update screen data list
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		// Menu info
		AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;

		// Configure pop up menu
		menu.setHeaderTitle(establishments.get(info.position).toString());
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.editmenu, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.itemEdit:
			Establishment estab = establishments.get(info.position);
			Intent intent = new Intent(SearchableActivity.this,
					EditEstablishActivity.class);
			intent.putExtra("id", estab.getId());
			startActivity(intent);
			return true;

		case R.id.itemDelete:
			datasource.deleteEstablishment(establishments.get(info.position));
			// Update list view
			doMySearch(query);
			return true;

		default:
			break;
		}
		return true;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Establishment estab = establishments.get(position);
		// Put info to view details
		Intent intent = new Intent(SearchableActivity.this,
				DetailsEstablishment.class);
		intent.putExtra("id", estab.getId());
		startActivity(intent);
		this.finish();
	}

	private void doMySearch(String query) {
		// Use simple cursor adapter to show the elements in a ListView
		establishments = datasource.searchAllEstablishments(query, aToz);
		adapter1 = new EstablishmentAdapter(this, R.layout.item,
				establishments, false);
		setListAdapter(adapter1);

		TextView results = (TextView) findViewById(R.id.txtResult);
		if (establishments.isEmpty()) {
			results.setText("Establishment not found");
			results.setVisibility(TextView.VISIBLE);
			results.setTextSize(25);
		}
		else{
			results.setVisibility(TextView.GONE);
		}
	}

	private void updateListView() {
		// Use simple cursor adapter to show the elements in a ListView
		establishments = datasource.searchAllEstablishments(query, aToz);
		adapter1 = new EstablishmentAdapter(this, R.layout.item,
				establishments, hideCheckBox);
		setListAdapter(adapter1);
	}

	private void chooseDisplayMode() {
		ArrayList<String> list = typeEstabDataSource.getAllTypeOfEstablishs();
		final CharSequence[] items = list
				.toArray(new CharSequence[list.size()]);

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Type of establishment");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				long id = typeEstabDataSource.getIdByName(items[item]
						.toString());
				Toast.makeText(getApplicationContext(), items[item].toString(),
						Toast.LENGTH_SHORT).show();
				// Get establishment by type of establishment
				updateListViewByType(id);
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private void switchSortMode() {
		aToz = !aToz;
		updateListView();
		// Update screen data list
		adapter1.notifyDataSetChanged();

	}

	private void updateListViewByType(long idTypeOfEstablishment) {
		establishments = datasource.getAllEstablishmentsByEstablishment(
				idTypeOfEstablishment, aToz, query);
		adapter1 = new EstablishmentAdapter(this, R.layout.item,
				establishments, hideCheckBox);
		setListAdapter(adapter1);
	}
}
